package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.enums.WxMsgTypeEnum;
import com.jingdianjichi.wx.utils.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

//        从微信官方文档中获取返回格式：
//        String msg = "<xml>\n" +
//                "  <ToUserName><![CDATA["+ fromUserName +"]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA["+ toUserName +"]]></FromUserName>\n" +
//                "  <CreateTime>12345678</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[你好]]></Content>\n" +
//                "</xml>";

/**
 * 用户发送文本"验证码"时，给用户反馈一个四位数的验证码：
 */
@Component
public class ReceiveTextMsgHandler implements WxChatMsgHandler{
    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxMsgTypeEnum getMsgTypeEnum() {
        return WxMsgTypeEnum.SEND_TEXT;
    }
    @Override
    public String dealMsg(Map<String, String> messageMap) {
        //获取用户信息：
        String adminName = messageMap.get("ToUserName");
        String userName = messageMap.get("FromUserName");
        String userContent = messageMap.get("Content");

        // 验证码生成：
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(r.nextInt(10));
        }
        String code = sb.toString();//验证码

        String msg = "您的验证码为："+code + ",五分钟内有效";

        //将验证码 放到缓存中，并设置过期时间，
        // 将验证码作为key，openId作为Value
        redisUtil.setEx(code,userName,5L, TimeUnit.MINUTES);

        String sendMsgCode = "<xml>\n" +
                "  <ToUserName><![CDATA["+ userName +"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+ adminName +"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+ msg + "]]></Content>\n" +
                "</xml>";

        if(userContent.equals("验证码")){
            return sendMsgCode;
        }
        return null;
    }
}
